package com.je.meta.rpc.project.impl;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.rpc.project.ProjectInfoRpcService;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@RpcSchema(schemaId = "projectInfoRpcService")
public class ProjectInfoRpcServiceImpl implements ProjectInfoRpcService {

    @Autowired
    private MetaService metaService;

    @Override
    public List<DynaBean> findAllWithOrder(String tableCode, String infoLevelGlSql) {
        if (Strings.isNullOrEmpty(infoLevelGlSql)) {
            return metaService.select(tableCode, ConditionsWrapper.builder().orderByAsc("SY_CREATETIME"));
        }
        return metaService.select(tableCode, ConditionsWrapper.builder().apply(infoLevelGlSql).orderByAsc("SY_CREATETIME"));
    }

    @Override
    public DynaBean findProjectByPk(String tableCode, String projectId, String orgTableCode,
                                    String orgId, String userTableCode, String systemDeptUserIdColumnCode
            , String deptUserId, String userGlSql, String userForeignKeyOrgIdField) {
        DynaBean project = metaService.selectOneByPk(tableCode, projectId);
        if (project == null) {
            return null;
        }
        DynaBean orgBean = null;
        if (Strings.isNullOrEmpty(orgId)) {
            List<DynaBean> projectUserBeanList = metaService.select(userTableCode, ConditionsWrapper.builder()
                    .eq(systemDeptUserIdColumnCode, deptUserId).apply(userGlSql).orderByAsc("SY_CREATETIME"));
            if (projectUserBeanList == null || projectUserBeanList.isEmpty()) {
                return null;
            }
            DynaBean user = projectUserBeanList.get(0);
            orgId = user.getStr(userForeignKeyOrgIdField);
        }
        orgBean = metaService.selectOneByPk(orgTableCode, orgId);
        project.set("orgBean", orgBean.getValues());
        return project;
    }

}
